<template>
  <t-row :gutter="16" class="row-container" style="display: flex;align-items: stretch;">
    <t-col style="flex: 1;display: flex;">
      <t-card
        :title="t('pages.dashboardBase.topPanel.analysis.report')"
  
        class="dashboard-chart-card"
        :bordered="false"
      >
      <template #title>
        <span style="display: inline-flex; align-items: center;">
          {{ t('pages.dashboardBase.topPanel.analysis.report') }}
          <t-tooltip content="" placement="top">
            <t-icon 
              name="help-circle" 
              style="margin-left: 6px; color: var(--td-text-color-placeholder); cursor: pointer;"
            />
          </t-tooltip>
        </span>
      </template>
        <!-- <template #description> -->
          <t-radio-group v-model="report" size="small" variant="default-filled" @change="handleGetHomeReportStatistics">
            <t-radio-button v-for="_ in timeDate" :key="'report'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
        <!-- </template> -->
        <t-descriptions :column="1" style="margin-top: 30px;" size="large">
          <t-descriptions-item label="总数">{{ reportDate.allNum }} 条</t-descriptions-item>
          <t-descriptions-item label="废单">{{ reportDate.feiDanNum }} 条</t-descriptions-item>
          <t-descriptions-item label="公海">{{ reportDate.ghNum }} 条</t-descriptions-item>
        </t-descriptions>

      </t-card>
    </t-col>
    <t-col style="flex: 1;display: flex;">
      <t-card
        :title="t('pages.dashboardBase.topPanel.analysis.design')"
        class="dashboard-chart-card"
        :bordered="false"
      >
      <template #title>
        <span style="display: inline-flex; align-items: center;">
          {{ t('pages.dashboardBase.topPanel.analysis.design') }}
          <t-tooltip content="" placement="top">
            <t-icon 
              name="help-circle" 
              style="margin-left: 6px; color: var(--td-text-color-placeholder); cursor: pointer;"
            />
          </t-tooltip>
        </span>
      </template>
        <!-- <template #subtitle> -->
          <t-radio-group v-model="Designer" size="small" variant="default-filled" @change="handleGetHomeDesignerStatistics">
            <t-radio-button v-for="_ in timeDate" :key="'designer'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
        <!-- </template> -->
        <t-descriptions :column="1" style="margin-top: 30px;" size="large">
          <t-descriptions-item label="总数">{{ DesignerDate.allNum }} 条</t-descriptions-item>
          <t-descriptions-item label="废单">{{ DesignerDate.feiDanNum }} 条</t-descriptions-item>
          <t-descriptions-item label="公海">{{ DesignerDate.ghNum }} 条</t-descriptions-item>
        </t-descriptions>

      </t-card>
    </t-col>
    <t-col style="flex: 1;display: flex;">
      <t-card
        :title="t('pages.dashboardBase.topPanel.analysis.engineering')"
        
        class="dashboard-chart-card"
        :bordered="false"
      >
      <template #title>
        <span style="display: inline-flex; align-items: center;">
          {{ t('pages.dashboardBase.topPanel.analysis.engineering') }}
          <t-tooltip content="" placement="top">
            <t-icon 
              name="help-circle" 
              style="margin-left: 6px; color: var(--td-text-color-placeholder); cursor: pointer;"
            />
          </t-tooltip>
        </span>
      </template>
      <t-descriptions :column="1">
          <t-descriptions-item label="待开工">{{ engineeringStatistics.daiKaiGong }} 套</t-descriptions-item>
          <t-descriptions-item label="施工中">{{ engineeringStatistics.shiGongZhong }} 套</t-descriptions-item>
          <t-descriptions-item label="工程已竣工">{{ engineeringStatistics.junGong }} 套</t-descriptions-item>
          <t-descriptions-item label="工程已停工">{{ engineeringStatistics.tingGong }} 套</t-descriptions-item>
          <t-descriptions-item label="退单">{{ engineeringStatistics.tuiDan }} 套</t-descriptions-item>
        </t-descriptions>

      </t-card>
    </t-col>
    <t-col style="flex: 1;display: flex;">
      <t-card
        :title="t('pages.dashboardBase.topPanel.analysis.money')"
        
        class="dashboard-chart-card"
        :bordered="false"
      >
        <template #title>
          <span style="display: inline-flex; align-items: center;">
            {{ t('pages.dashboardBase.topPanel.analysis.money') }}
            <t-tooltip content="" placement="top">
              <t-icon 
                name="help-circle" 
                style="margin-left: 6px; color: var(--td-text-color-placeholder); cursor: pointer;"
              />
            </t-tooltip>
          </span>
        </template>
        <!-- <template #subtitle> -->
          <t-radio-group v-model="money" size="small" variant="default-filled" @change="handleGetHomeMoneyStatistics">
            <t-radio-button v-for="_ in timeDate" :key="'money'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
        <!-- </template> -->
        <t-descriptions :column="1" style="margin-top: 30px;" size="large">
          <t-descriptions-item label="整装合同">{{ moneyDate.zhengMoney }} 元</t-descriptions-item>
          <t-descriptions-item label="产品合同">{{ moneyDate.productMoney }} 元</t-descriptions-item>
          <t-descriptions-item label="单品合同">{{ moneyDate.singleMoney }} 元</t-descriptions-item>
        </t-descriptions>

      </t-card>
    </t-col>
    <t-col style="flex: 1;display: flex;">
      <t-card
        :title="t('pages.dashboardBase.topPanel.analysis.channels')"

        class="dashboard-chart-card"
        :bordered="false"
      >
      <template #title>
        <span style="display: inline-flex; align-items: center;">
          {{ t('pages.dashboardBase.topPanel.analysis.channels') }}
          <t-tooltip content="" placement="top">
            <t-icon 
              name="help-circle" 
              style="margin-left: 6px; color: var(--td-text-color-placeholder); cursor: pointer;"
            />
          </t-tooltip>
        </span>
      </template>
        <!-- <template #actions> -->
          <!--  -->
          <t-radio-group v-model="channel" size="small" variant="default-filled" @change="handleGetHomeChannelStatistics">
            <t-radio-button v-for="_ in timeDate" :key="'ch'+_.value" :value="_.value"> {{ _.name }}</t-radio-button>
          </t-radio-group>
        <!-- </template> -->
        <div
          id="countContainer"
          class="dashboard-chart-container"
          :style="{ width: `${resizeTime * 245}px`, height: `${resizeTime * 280}px`, margin: '0 auto' }"
        />
      </t-card>
    </t-col>
  </t-row>
</template>

<script setup lang="ts">
import { useWindowSize } from '@vueuse/core';
import { LineChart, PieChart } from 'echarts/charts';
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { computed, nextTick, onDeactivated, onMounted, ref, watch } from 'vue';

import { t } from '@/locales';
import { useSettingStore } from '@/store';
import { changeChartsTheme } from '@/utils/color';
import { LAST_7_DAYS } from '@/utils/date';

import { getLineChartDataSet, getPieChartDataSet } from '../index';
import { homeChannelStatistics, homeDesignerStatistics, homeEngineeringStatistics, homeMoneyStatistics, homeReportStatistics } from '@/api/dashboard/base';
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';

echarts.use([TooltipComponent, LegendComponent, PieChart, GridComponent, LineChart, CanvasRenderer]);

const getThisMonth = (checkedValues?: string[]) => {
  let date: Date;
  if (!checkedValues || checkedValues.length === 0) {
    date = new Date();
    return `${date.getFullYear()}-${date.getMonth() + 1}`;
  }
  date = new Date(checkedValues[0]);
  const date2 = new Date(checkedValues[1]);

  const startMonth = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : `0${date.getMonth() + 1}`;
  const endMonth = date2.getMonth() + 1 > 9 ? date2.getMonth() + 1 : `0${date2.getMonth() + 1}`;
  return `${date.getFullYear()}-${startMonth}  至  ${date2.getFullYear()}-${endMonth}`;
};

const store = useSettingStore();
const resizeTime = ref(1);

const chartColors = computed(() => store.chartColors);


// monitorChart
let countContainer: HTMLElement;
let countChart: echarts.ECharts;
const renderCountChart = () => {
  if (!countContainer) {
    countContainer = document.getElementById('countContainer');
  }
  countChart = echarts.init(countContainer);
  countChart.setOption(getPieChartDataSet(chartColors.value));

  // 取消之前高亮的图形
  countChart.dispatchAction({
    type: 'downplay',
    seriesIndex: 0,
    dataIndex: -1,
  });
  // 高亮当前图形
  countChart.dispatchAction({
    type: 'highlight',
    seriesIndex: 0,
    dataIndex: 1,
  });
  // 显示 tooltip
  countChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: 1,
  });
};

const renderCharts = () => {
  renderCountChart();
};

// chartSize update
const updateContainer = () => {
  if (document.documentElement.clientWidth >= 1400 && document.documentElement.clientWidth < 1920) {
    resizeTime.value = Number((document.documentElement.clientWidth / 2080).toFixed(2));
  } else if (document.documentElement.clientWidth < 1080) {
    resizeTime.value = Number((document.documentElement.clientWidth / 1080).toFixed(2));
  } else {
    resizeTime.value = 1;
  }

  countChart.resize({
    width: resizeTime.value * 245,
    height: resizeTime.value * 280,
  });
};
const report = ref(2)
const reportDate = ref({
  allNum: 0,
  feiDanNum: 0,
  ghNum: 0
})
const handleGetHomeReportStatistics = () => {

  const params = {
    beginTime:'',
    endTime:'',
  }
  const now = new Date();
  
  switch(report.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
  homeReportStatistics(params).then((data) => {
     reportDate.value = data
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 设计
const Designer = ref(2)
const DesignerDate = ref({
  allNum: 0,
  feiDanNum: 0,
  ghNum: 0
})
const handleGetHomeDesignerStatistics = () => {

  const params = {
    beginTime:'',
    endTime:'',
  }
  const now = new Date();
  
  switch(Designer.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      // 不传日期参数
      params.beginTime='';
      params.endTime='';
      break;
  }
  homeDesignerStatistics(params).then((data) => {
     DesignerDate.value = data
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
// 施工
const engineeringStatistics = ref({
  tuiDan: 0,
  tingGong: 0,
  shiGongZhong: 0,
  junGong: 0,
  daiKaiGong: 0,
})
const handleGetHomeEngineeringStatistics = () => {


homeEngineeringStatistics().then((data) => {
   console.log(data,'ddd');
   engineeringStatistics.value = data
  })
  .catch(({ message }) => {
    MessagePlugin.error(message);
  });
}
// 产值
const money = ref(4)
const moneyDate = ref({
  zhengMoney: 0,
  productMoney: 0,
  singleMoney: 0
})
const handleGetHomeMoneyStatistics = () => {

  const params = {
    beginTime:'',
    endTime:'',
  }
  const now = new Date();
  
  switch(money.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      params.beginTime='';
      params.endTime='';
      break;
  }
  homeMoneyStatistics(params).then((data) => {
     moneyDate.value = data
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    });
}
const channel = ref(2)
const channelDate = ref<Array<{name: string; value: number}>>([]);
const handleGetHomeChannelStatistics = () => {

  const params = {
    beginTime:'',
    endTime:'',
  }
  const now = new Date();
  
  switch(channel.value) {
    case 1: // 本周
      const firstDayOfWeek = new Date(now.setDate(now.getDate() - now.getDay() + (now.getDay() === 0 ? -6 : 1)));
      const lastDayOfWeek = new Date(firstDayOfWeek);
      lastDayOfWeek.setDate(firstDayOfWeek.getDate() + 6);
      
      params.beginTime = dayjs(firstDayOfWeek).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfWeek).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 2: // 本月
      const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDayOfMonth = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      params.beginTime = dayjs(firstDayOfMonth).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfMonth).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 3: // 本年
      const firstDayOfYear = new Date(now.getFullYear(), 0, 1);
      const lastDayOfYear = new Date(now.getFullYear(), 11, 31);
      
      params.beginTime = dayjs(firstDayOfYear).format('YYYY-MM-DD 00:00:00');
      params.endTime = dayjs(lastDayOfYear).format('YYYY-MM-DD 23:59:59');
      break;
      
    case 4: // 全部
      params.beginTime='';
      params.endTime='';
      break;
  }
  // 更新图表
  homeChannelStatistics(params).then((data) => {
    // 确保数据格式正确
    channelDate.value = Array.isArray(data) ? data : [];
    
    // 更新图表
    if (countChart) {
      countChart.setOption(getPieChartDataSet({
        ...chartColors.value,
        channelData: channelDate.value
      }));
    }
  }).catch(({ message }) => {
    MessagePlugin.error(message);
    channelDate.value = []; // 出错时清空数据
  });
}
onMounted(() => {
  handleGetHomeReportStatistics()
  handleGetHomeDesignerStatistics()
  handleGetHomeEngineeringStatistics()
  handleGetHomeMoneyStatistics()
  handleGetHomeChannelStatistics()
  renderCharts();
  nextTick(() => {
    updateContainer();
  });
});

const { width, height } = useWindowSize();
watch([width, height], () => {
  updateContainer();
});

onDeactivated(() => {
  storeModeWatch();
  storeBrandThemeWatch();
  storeSidebarCompactWatch();
});

const currentMonth = ref(getThisMonth());

const storeBrandThemeWatch = watch(
  () => store.brandTheme,
  () => {
    changeChartsTheme([countChart]);
  },
);

const storeSidebarCompactWatch = watch(
  () => store.isSidebarCompact,
  () => {
    if (store.isSidebarCompact) {
      nextTick(() => {
        updateContainer();
      });
    } else {
      setTimeout(() => {
        updateContainer();
      }, 180);
    }
  },
);

const storeModeWatch = watch(
  () => store.mode,
  () => {
    [countChart].forEach((item) => {
      item.dispose();
    });

    renderCharts();
  },
);



const timeDate = [
  {value:1,name:'本周'},
  {value:2,name:'本月'},
  {value:3,name:'本年'},
  {value:4,name:'全部'},
  ]

function homeChannelSStatistics(params: { beginTime: string; endTime: string; }) {
  throw new Error('Function not implemented.');
}
</script>

<style lang="less" scoped>
.dashboard-chart-card {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);

  :deep(.t-card__header) {
    padding: 0;
  }

  :deep(.t-card__body) {
    padding: 0;
    margin-top: var(--td-comp-margin-xxl);
  }

  :deep(.t-card__title) {
    font: var(--td-font-title-large);
    font-weight: 400;
  }
}
</style>
